package interview.base;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

public class ThreadTest {
private static Logger log = LoggerFactory.getLogger(ThreadTest.class);
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ThreadTest threadTest = new ThreadTest();
        //threadTest.testJoin();
        threadTest.testCallable();


    }


    public void testJoin() throws InterruptedException {
        Thread main = Thread.currentThread();
        System.out.println(main.getName());
        Thread thread = new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
            }
        });

        thread.start();
        //主线程执行到这里会停止，等待着让thread去执行完再执行
        thread.join();
        System.out.println(Thread.currentThread());
    }


    public void  testCallable() throws ExecutionException, InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>());
        FutureTask futureTask = new FutureTask(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(3000);
                // 返回一句话
                return "我是子线程"+Thread.currentThread().getName();
            }
        });
// 把任务提交到线程池中，线程池会分配线程帮我们执行任务
        executor.submit(futureTask);
// 得到任务执行的结果
        String result = (String) futureTask.get();
        System.out.println("result is:"+result);
    }


}
